#include "StdAfx.h"
#include "ADOQuery.h"

CADOQuery::CADOQuery(void):
	m_SQL(""),
	m_Active(FALSE),
	m_pConn(0),
	m_DataSet(__uuidof(Recordset))
{
}

CADOQuery::~CADOQuery(void)
{
	Close();
	//if (m_DataSet != NULL)
	//{
	//	m_DataSet.Release();
	//}
	m_DataSet = NULL;
}

void CADOQuery::SetSQL(CString ASQL)
{
	m_SQL = ASQL;
}

CString CADOQuery::GetSQL(void)
{
	return m_SQL;
}

CADOConnection* CADOQuery::GetConn(void)
{
	return m_pConn;
}

void CADOQuery::SetConnection(CADOConnection* AConn)
{
	m_pConn = AConn;
}

void CADOQuery::Open(void)
{
	if ((m_SQL != "") && (m_pConn != 0))
	{
		//m_DataSet = m_pConn->Execute(m_SQL);
		m_DataSet->Open(_bstr_t(m_SQL.GetBuffer()), m_pConn->m_Conn.GetInterfacePtr(), 
				adOpenDynamic, adLockOptimistic, adCmdText);
		m_Active = TRUE;
	}
}

void CADOQuery::Close(void)
{
	if (m_Active && (m_DataSet != NULL))
	{
		m_DataSet->Close();
		m_Active = FALSE;
	}
}

void CADOQuery::First(void)
{
	if (!m_DataSet->ADOBOF)
		m_DataSet->MoveFirst();
}

void CADOQuery::Last(void)
{
	if (!m_DataSet->ADOEOF)
		m_DataSet->MoveLast();
}

void CADOQuery::Next(void)
{
	m_DataSet->MoveNext();
}

void CADOQuery::Prev(void)
{
	m_DataSet->MovePrevious();
}

BOOL CADOQuery::Bof(void)
{
	return m_DataSet->ADOBOF;
}

BOOL CADOQuery::Eof(void)
{
	return m_DataSet->ADOEOF;
}

int CADOQuery::FieldsCount(void)
{
	return m_DataSet->Fields->Count;
}

FieldsPtr CADOQuery::GetFields(void)
{
	return m_DataSet->Fields;
}

_variant_t CADOQuery::FieldValueByIndex(int Index)
{
	return m_DataSet->Fields->Item[Index]->Value;
}

_variant_t CADOQuery::FieldValueByName(CString AName)
{
	return m_DataSet->GetCollect(AName.GetBuffer());
}

BOOL CADOQuery::ExecSQL()
{
	try
	{	
		m_pConn->Execute(m_SQL);
	}
	catch(...)
	{	
		return FALSE;
	}
	return TRUE;
}

int CADOQuery::FieldValueAsInt(CString AName)
{
	return FieldValueByName(AName);
}

int CADOQuery::FieldValueAsInt(int Index)
{
	return FieldValueByIndex(Index);
}

CString CADOQuery::FieldValueAsString(CString AName)
{
	_variant_t var = FieldValueByName(AName);
	if (var.vt == VT_NULL)
		return "";
	else
		return (LPCSTR)_bstr_t(var);
}

CString CADOQuery::FieldValueAsString(int Index)
{
	_variant_t var = FieldValueByIndex(Index);
	if (var.vt == VT_NULL)
		return "";
	else
		return (LPCSTR)_bstr_t(var);
}

void CADOQuery::Append()
{
	m_DataSet->AddNew();
}

void CADOQuery::Post()
{
	m_DataSet->Update();
}

void CADOQuery::Delete()
{
	m_DataSet->Delete(adAffectCurrent);
	m_DataSet->Update();
}

void CADOQuery::SetFieldValueByName(CString AFieldName, _variant_t Value)
{
	m_DataSet->PutCollect(AFieldName.GetBuffer(), Value);
}